/**
 * http://usejsdoc.org/
 * @class app
 */

/**
 * 设置路径全局变量 
 */
global.BASE_DIR = __dirname,
global.APP = BASE_DIR + '/app/';
global.CON = APP + '/controller/',
global.CORE = APP + '/core/',
global.MODEL = APP + '/model/',
global.LOG = BASE_DIR + '/log/',
global.LIB = BASE_DIR + '/node_modules/',
global.CONF = BASE_DIR + '/conf/',
global.STATIC = BASE_DIR + '/public/',
global.VIEW = BASE_DIR + '/view/';

/***
 * modules 引入
 */
global.lib = {
	http : require('http'),
	fs : require('fs'),
	url : require('url'),
	querystring : require('querystring'),
	httpParam : require(LIB+'http_param'),
	staticModule : require(LIB+'static_module'),
	router : require(CORE+'router'),
	action : require(CORE+'action'),
	jade : require('jade'),
	socket : require('socket.io'),
	path : require('path'),
	//parseCookie : require('connect').utils.parseCookie,
	session : require(LIB+'node_session'),
	util : require('util')
};


/**主要存储socket在线用户信息*/
global.onlineList = [];

/**创建http服务*/
global.app = lib.http.createServer(function(req,res){
	res.render = function(){
		var template = arguments[0];
		var options = arguments[1];
		var str = lib.fs.readFileSync(template,'utf8');
		var fn = lib.jade.compile(str,{filename:template,pretty:true});
		
		var page = fn(options);
		res.writeHeader(200,{'Content-Type':'text/html'});
		res.end(page);
	};
	lib.router.router(res,req);
}).listen(8080);

/**启动本系统的socket 服务*/
global.io = lib.socket.listen(app);

var time = 0;
io.sockets.on('connection',function(socket){
	var username = sessionLib.username;
	if(!onlineList[username]){
		onlineList[username] = socket;
	}
	
	var refresh_online = function(){
		var n = [];
		for (var i in onlineList) {
			n.push(i);
		}
		
		var message = lib.fs.readFileSync(BASE_DIR+'/live_data.txt','utf8');
		socket.emit('live_data',message);
		io.socket.emt('online_list',n);//所有人广播
		
	}; 
	
	refresh_online();
	
	/**确保每一次发送一个socket*/
	if(time > 0 ){
		return;
	}
	
	socket.on('public',function(data){
		var insertMsg = "<li><span class='icon-user'></span>"+
			"<span class='live_user_name text_sucess'>[devintam]</span>"+
			"<span class='live_message text_info'>"+data.msg+"</span></li>";
		writeFile({'msg':insertMsg,'data':data},function(data){
			io.sockets.emit('msg',data);
		});
		
	});
	
	socket.on('disconnect',function(){
		delete onlineList[username];
		refresh_online();
	});
	time++;
});

function writeFile(data,callback){
	var message = lib.fs.readFileSync(BASE_DIR+'/live_data.txt','utf8');
	lib.fs.writeFile(BASE_DIR+'/live_data.txt',message + data.msg,function(err){
		if(err){
			throw err;
		}
		callback(data.data);
	});
}